import React from 'react'
import util from '../../util'
import { TitleBar, Link, Table } from '../../ui-components'
import { connect } from 'react-redux'
import mime from 'mime-types'
import style from './style.document'
import { u } from '../../actions/util'

export default
@connect(({ onboardingTemplates }) => ({ onboardingTemplates }))
class UserDocuments extends React.Component {

	componentWillReceiveProps(props) {
		if (util.isNull(this.props.profile) && !util.isNull(props.profile)) {
			this.fetchDocuments(props)
		}
	}

	componentWillUnmount() {
		this.props.resetOnboardingTemplates()
	}

  // 下载文档
  downloadDocument(doc) {
    this.props.downloadDocument(doc.documentId, res => {
      location.href = res.data.presignedUrl
    })
  } 

	fetchDocuments(props) {
		props = props || this.props
    this.props.fetchOnboardingTemplate(props.location.query.onboardingTemplateId)
	}

  fetchUserProfile(props) {
    props = props || this.props
		this.props.fetchUserProfile(u.userId)
  }

  componentDidMount() {
		this.fetchUserProfile()
    this.fetchDocuments()
  }

	render() {
		return (
			<div>
        <TitleBar
          label="公司文档"
        />
				<Table
					model={
						{
							documentName: '文档',
							documentType: '类型',
							documentSize: '大小'
						}
					}
          map={
            {
              documentSize: v => util.size(v),
              documentName: (v, doc) => !doc.description? (
                <Link label={v} onClick={() => this.downloadDocument(doc)}/>
              ): (
                <div>
                  <Link label={v} onClick={() => this.downloadDocument(doc)}/>
                  <div className={style['document-description']}>{ doc.description }</div>
                </div>
              )
            }
          }
					data={ this.props.onboardingTemplates.template.onboardingDocumentVOs }
				/>
			</div>
		)
	}
}
